package toman;

import javax.persistence.TemporalType;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * The base class for queries that fetch a list of result TOs only and do not have parameters.
 * <p>
 * User: zslajchrt
 * Date: 4.5.11
 * Time: 10:15
 */
public abstract class ListTOQuery<T> implements TOQuery<T> {

    protected int firstResult = -1;
    protected int maxResults = -1;

    protected final Class<T> toClass;
    protected final TOMan toman;

    protected ListTOQuery(TOMan toman, Class<T> toClass) {
        this.toman = toman;
        this.toClass = toClass;
    }

    public TOQuery setFirstResult(int index) {
        firstResult = index;
        return this;
    }

    public TOQuery setMaxResults(int max) {
        maxResults = max;
        return this;
    }

    public List<T> getResults() {
        try {
            List<Object> rawDataList = createRawDataList();
            if (firstResult >= 0 || maxResults >= 0) {
                int fr = firstResult < 0 ? 0 : firstResult;
                int mr = maxResults < 0 ? rawDataList.size() : maxResults;
                rawDataList = rawDataList.subList(fr, mr);
            }
            return new TOList<T>(rawDataList, toClass, toman);
        } catch (SQLException e) {
            throw new IllegalArgumentException(e);
        }
    }

    protected abstract List<Object> createRawDataList() throws SQLException;

    public T getSingleResult() {
        return null;
    }

    public Object getInternalQuery() {
        return null;
    }

    public ParameterizedQuery setParameter(String paramName, Object value) {
        throw new UnsupportedOperationException();
    }

    public ParameterizedQuery setParameter(String paramName, Date value, TemporalType type) {
        throw new UnsupportedOperationException();
    }

    public Set<String> getParameterNames() {
        return Collections.emptySet();
    }
}
